﻿using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using System.Collections.Concurrent;
using Microsoft.Office.Interop.Excel;
using OfficeExcelApplication = Microsoft.Office.Interop.Excel.Application;
using SUNRPA.CONTROLS.IMPL.util;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;

namespace SUNRPA.CONTROLS.IMPL.controls {
    public class WriteToExcelNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            WriteToExcelNParam? param = item.ControlParam as WriteToExcelNParam;
            string writeObj = param.WriteObjectName;
            Workbook wb = this.GetObjVar<ExcelModel>(ref writeObj, globleData).WorkBookValue as Workbook;
            if(wb == null) { 
                throw new RpaRuntimeException(String.Format("Excel对象{0}不存在", writeObj));
            }
            ExcelUtil excelUtil = new ExcelUtil();
            excelUtil.SetApp(wb);

            string sheetName = param.SheetName;
            this.GetStringVar(ref sheetName, globleData);

            int range = param.Range;
            int writeWay = param.WriteWay;
            string rowString = param.Row;
            string columnString = param.Column;
            this.GetStringVar(ref rowString, globleData);
            this.GetStringVar(ref columnString, globleData);
            int rowNum = excelUtil.GetRowNum(rowString, sheetName);
            int columnNum = excelUtil.GetColumnNum(columnString, sheetName);
            string writeContent = param.WriteContent;
            
            //写入内容可能是字符串也可能是变量，如果是变量的话可能为字符串或者为一个列表，若二者都不是则为错误参数
            object objContent;
            try { 
                objContent = this.GetObjVar<object>(ref writeContent, globleData);
            }catch(RpaRuntimeException e) { 
                this.GetStringVar(ref writeContent, globleData);
                objContent = writeContent;
            }

            if(range == 0) { 
                //列
                excelUtil.FillColumn2End(rowNum, columnNum, sheetName, objContent, writeWay);
            }else if(range == 1) {
                //行
                excelUtil.FillRow2End(rowNum, columnNum, sheetName, objContent, writeWay);
            } else { 
                //单元格
                excelUtil.FillCell(rowNum, columnNum, sheetName, objContent);
            }
            return currentIndex;
        }
    }
}
